package com.moxigua.iotbox.func.manual;


import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import com.google.gson.Gson;
import com.moxigua.iotbox.R;
import com.moxigua.iotbox.base.BaseApplication;
import com.moxigua.iotbox.base.BaseFragment;
import com.moxigua.iotbox.base.Constants;
import com.moxigua.iotbox.bean.BaseRequest;
import com.moxigua.iotbox.bean.MqttAction;
import com.moxigua.iotbox.bean.RequestOperateDevices;
import com.moxigua.iotbox.bean.ResponseDeviceStatusAction;
import com.moxigua.iotbox.func.MqttClientHepler;
import com.moxigua.iotbox.func.event.BaseEvent;
import com.moxigua.iotbox.util.SPUtils;
import com.moxigua.iotbox.util.TimeUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.moxigua.iotbox.util.TimeUtil.FORMAT_DATE_TIME;

/**
 * A simple {@link Fragment} subclass.
 * 手动操作页面
 */
public class ManualFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, CompoundButton.OnCheckedChangeListener {


    @BindView(R.id.tv_time)
    TextView mTvTime;
    @BindView(R.id.sw_head)
    Switch mSwHead;
    @BindView(R.id.sw_water)
    Switch mSwWater;
    @BindView(R.id.sw_light)
    Switch mSwLight;
    @BindView(R.id.sw_wind)
    Switch mSwWind;
    @BindView(R.id.sw_curtain)
    Switch mSwCurtain;
    @BindView(R.id.sw_water_pump)
    Switch mSwWaterPump;

    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout mSwipeLayout;
    private Gson mGson;
    private boolean operateEnableLock = true;  // 操作锁，防止连续操作导致的设备操作崩溃，true时使能，false不能

    public ManualFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mGson = new Gson();
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }
        View view = inflater.inflate(R.layout.fragment_manual, container, false);
        ButterKnife.bind(this, view);
        mSwipeLayout.setOnRefreshListener(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onRefresh();
            }
        }, 1500);
        mSwHead.setOnCheckedChangeListener(this);
        mSwWater.setOnCheckedChangeListener(this);
        mSwLight.setOnCheckedChangeListener(this);
        mSwWind.setOnCheckedChangeListener(this);
        mSwCurtain.setOnCheckedChangeListener(this);
        mSwWaterPump.setOnCheckedChangeListener(this);
        return view;
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh() {
        if (BaseApplication.isOnline() && MqttClientHepler.getInstance().isConnect()) {
            //传递MQTT指令，等待采集点返回数据
            MqttAction<BaseRequest,Double> requestStatusAction = new MqttAction<>();
            requestStatusAction.setMetric(Constants.METRIC_REQUEST_DEVICE_STATUS);
            BaseRequest requestStatus = new BaseRequest();
            int randomPacketId = (int) (Math.random() * 10000);
            BaseApplication.setLastPacketId(randomPacketId);
            requestStatus.setPacketID(randomPacketId);
            requestStatus.setClientid((Integer) SPUtils.get(Constants.SP_CLIENT_ID,0));
            requestStatusAction.setTags(requestStatus);
            requestStatusAction.setValue(Double.valueOf(0));
            String payload = "[" + new Gson().toJson(requestStatusAction) + "]";
            MqttClientHepler.getInstance().publish(Constants.TOPIC_PUB_DEV, 1, payload.getBytes());
        } else {
            showShortToast("尚未连接\n稍后再试");
            mSwipeLayout.setRefreshing(false);
        }
    }

    /**
     * 请求更改设备的开关状态
     * @param deviceId
     * @param operate
     */
    public void requestOperateDevice(int deviceId, boolean operate,CompoundButton button) {
        if (MqttClientHepler.getInstance().isConnect() && operateEnableLock) {
            //只有当设备在线并且使能锁正常时才能发送指令
            MqttAction<RequestOperateDevices,Integer> requestOperateAction = new MqttAction<>();
            requestOperateAction.setMetric(Constants.METRIC_REQUEST_OPERATE);
            requestOperateAction.setValue((operate?1:0));
            RequestOperateDevices requestStatus = new RequestOperateDevices();
            int randomPacketId = (int) (Math.random() * 10000);
            BaseApplication.setLastPacketId(randomPacketId);
            requestStatus.setPacketID(randomPacketId);
            requestStatus.setClientid((Integer) SPUtils.get(Constants.SP_CLIENT_ID,0));
            requestStatus.setDeviceID(deviceId);
            requestOperateAction.setTags(requestStatus);
            String payload = "[" + new Gson().toJson(requestOperateAction) + "]";
            MqttClientHepler.getInstance().publish(Constants.TOPIC_PUB_DEV, 1, payload.getBytes());
            operateEnableLock = false; //禁用操作
        } else if (!operateEnableLock){
            showShortToast("尚未使能\n稍后再试");
        }else {
            showShortToast("尚未连接\n稍后再试");
            button.setChecked(!operate);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseEvent(BaseEvent event) {
        if (event.topic.equals(Constants.TOPIC_SUB_REMOTE)) {
            mSwipeLayout.setRefreshing(false);
            //收到的数据格式为数组
            String json = event.message.toString();
            if (json.contains("\"ResponseDeviceStatus\"")) {
                Logger.json(json);
                mTvTime.setText(TimeUtil.longToString(new Date().getTime(), FORMAT_DATE_TIME));
                mSwipeLayout.setRefreshing(false);
                String jsonStr = json.substring(1, json.length() - 1);  //去除最外侧的[]
                ResponseDeviceStatusAction mqttAction = mGson.fromJson(jsonStr, ResponseDeviceStatusAction.class);
                List<ResponseDeviceStatusAction.ValueEntity> valueEntities = mqttAction.getValue();
                Switch switchBtn = null;
                for (ResponseDeviceStatusAction.ValueEntity valueEntity : valueEntities) {
                    switch (valueEntity.getDeviceID()) {
                        case Constants.DEVICE_ID_HEAD:
                            switchBtn = mSwHead;
                            break;
                        case Constants.DEVICE_ID_WATER:
                            switchBtn = mSwWater;
                            break;
                        case Constants.DEVICE_ID_LIGHT:
                            switchBtn = mSwLight;
                            break;
                        case Constants.DEVICE_ID_WIND:
                            switchBtn = mSwWind;
                            break;
                        case Constants.DEVICE_ID_CURTAIN:
                            switchBtn = mSwCurtain;
                            break;
                        case Constants.DEVICE_ID_WATER_PUMP:
                            switchBtn = mSwWaterPump;
                            break;
                        default:
                            switchBtn = null;
                    }
                    if (switchBtn != null) {
                        switchBtn.setOnCheckedChangeListener(null);
                        if (valueEntity.getStatus() == 1) {
                            switchBtn.setChecked(true);
                        } else {
                            switchBtn.setChecked(false);
                        }
                        switchBtn.setOnCheckedChangeListener(this);
                    }

                }
                //收到设备响应，使能操作
                operateEnableLock = true;
            } else if (json.contains("\"OffOnline\"")) {
                BaseApplication.setIsOnline(false);
                showShortToast("设备离线");
            }
        }
    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        switch (compoundButton.getId()) {
            case R.id.sw_head:
                Logger.d("正转"+b);
                requestOperateDevice(Constants.DEVICE_ID_HEAD,b,compoundButton);
                break;
            case R.id.sw_water:
                Logger.d("滴灌"+b);
                requestOperateDevice(Constants.DEVICE_ID_WATER,b,compoundButton);
                break;
            case R.id.sw_light:
                Logger.d("补光"+b);
                requestOperateDevice(Constants.DEVICE_ID_LIGHT,b,compoundButton);
                break;
            case R.id.sw_wind:
                Logger.d("通风"+b);
                requestOperateDevice(Constants.DEVICE_ID_WIND,b,compoundButton);
                break;
            case R.id.sw_curtain:
                Logger.d("反转"+b);
                requestOperateDevice(Constants.DEVICE_ID_CURTAIN,b,compoundButton);
            case R.id.sw_water_pump:
                Logger.d("反转"+b);
                requestOperateDevice(Constants.DEVICE_ID_WATER_PUMP,b,compoundButton);
                break;
        }
    }
}
